<template>
  <div>
    用户车辆管理
    <div style="margin: 8px 0; display: flex;">
      <a-input-search
        placeholder="请输入用户姓名"
        enter-button="搜 索"
        size="large"
        @search="onSearch"
        style="width: 500px;margin-right: 50px;"
      />
      <a-button
        type="primary"
        @click="handleAdd"
        style="width: 100px;height: 40px;"
        :disabled="disableFlag"
      >
        添加用户
      </a-button>
    </div>
    <a-table
      :columns="columns"
      :data-source="data"
      bordered
      style="width: 800px"
    >
      <template slot="userName" slot-scope="userName, record">
        <a-input
          type="text"
          :value="userName"
          v-if="record.recordAddFlag"
          @change="handleChange($event, record)"
        />
        <div v-else>{{ userName }}</div>
      </template>
      <template slot="carNumber" slot-scope="cars, record">
        <a-tag
          :closable="record.removeFlag"
          @close="log(record, car)"
          v-for="(car, i) in cars"
          :key="car"
          :color="colors[i % 5]"
        >
          {{ car }}
        </a-tag>
        <a-input
          v-if="record.addFlag || record.recordAddFlag"
          ref="input"
          type="text"
          size="small"
          :style="{ width: '78px' }"
          @change="handleInputChange"
        />
      </template>

      <template slot="operation" slot-scope="record">
        <div
          style="display: flex; "
          v-if="!record.removeFlag && !record.addFlag && !record.recordAddFlag"
        >
          <a-button
            :disabled="disableFlag"
            type="primary"
            @click="remove(record)"
          >
            删除车辆
          </a-button>

          <a-button :disabled="disableFlag" type="danger" @click="add(record)">
            添加车辆
          </a-button>

          <a-button
            :disabled="disableFlag"
            type="primary"
            @click="removeUser(record)"
          >
            删除用户
          </a-button>
        </div>

        <div
          style="display: flex; justify-content: space-between;width: 150px"
          v-else
        >
          <a-button type="primary" @click="save(record)">
            保存
          </a-button>
          <a-button type="danger" @click="recover">
            重置
          </a-button>
        </div>
      </template>
    </a-table>
  </div>
</template>

<script>
import {
  httpGet,
  SYS_GET_USER_CAR_INFO,
  SYS_GET_CAR_INFO,
  SYS_GET_USER_INFO
} from "../../api/api";
let key = require("./help");

const columns = [
  {
    title: "用户",
    dataIndex: "userName",
    width: "15%",
    scopedSlots: { customRender: "userName" }
  },
  {
    title: "车辆",
    dataIndex: "carNumber",
    width: "40%",
    scopedSlots: { customRender: "carNumber" }
  },
  {
    title: "操作",
    scopedSlots: { customRender: "operation" }
  }
];
export default {
  name: "UserCarManager",
  data() {
    return {
      disableFlag: false,
      columns: columns,
      data: [],
      colors: ["blue", "red", "pink", "yellow", "green"],
      newCar: "",
      carInfo: [],
      userInfo: []
    };
  },
  methods: {
    async getUserCarInfo() {
      const data = await httpGet(SYS_GET_USER_CAR_INFO + "?action=get", null);
      const carInfo = this.carInfo;
      const userInfo = this.userInfo;
      data.forEach((value, index, arr) => {
        arr[index].carNumber = [];
        userInfo.forEach(user => {
          if (user.key == value.user) {
            arr[index].userName = user.name;
          }
        });
        value.car.forEach(k => {
          carInfo.forEach(car => {
            if (car.key === k) {
              arr[index].carNumber.push(car.number);
            }
          });
        });
      });
      this.data = data;
      console.log(this.data);
    },
    log(record, car) {
      console.log(record, car);
      const index = record.carNumber.indexOf(car);
      record.car.splice(index, 1);
      record.carNumber.splice(index, 1);
    },
    remove(record) {
      this.disableFlag = true;
      record.removeFlag = true;
      this.data = [...this.data];
    },
    recover() {
      this.disableFlag = false;
      this.getUserCarInfo();
    },
    save(record) {
      if (record.recordAddFlag) {
        this.addSave(record);
      } else {
        this.modifySave(record);
      }
    },
    async addSave(record) {
      console.log(record);
      record.recordAddFlag = false;
      this.disableFlag = false;
      let flag = false;
      // 先确定 user
      this.userInfo.forEach(item => {
        if (item.name === record.userName) {
          record.user = item.key;
          flag = true;
        }
      });
      // 再确定 car
      this.carInfo.forEach(item => {
        if (item.number === this.newCar) {
          record.car.push(item.key);
          record.carNumber.push(item.number);
        }
      });
      if (flag) {
        console.log(record.userName + "用户存在");
        console.log(record);
        await httpGet(
          SYS_GET_USER_CAR_INFO + "?action=add&info=" + JSON.stringify(record),
          null
        );
      } else {
        this.$message.error("请在用户管理中先登记该用户！");
      }
      this.getUserCarInfo();
    },
    async modifySave(record) {
      if (record.addFlag === true) {
        let flag = true;
        this.carInfo.forEach(value => {
          if (value.number === this.newCar) {
            let redundant = false;
            record.car.forEach(item => {
              if (item === value.key) {
                redundant = true;
                this.$message.error("该车已经在列表中了！");
              }
            });
            if (!redundant) {
              record.car.push(value.key);
              record.carNumber.push(this.newCar);
            }
            flag = false;
          }
        });
        if (flag) {
          this.$message.error("该车未登记", 1);
          record.addFlag = false;
          record.removeFlag = false;
          this.disableFlag = false;
          return;
        }
      }
      record.addFlag = false;
      record.removeFlag = false;
      this.disableFlag = false;
      await httpGet(
        SYS_GET_USER_CAR_INFO + "?action=save&info=" + JSON.stringify(record),
        null
      );
      this.getUserCarInfo();
    },
    add(record) {
      console.log(record);
      record.addFlag = true;
      this.disableFlag = true;
      this.data = [...this.data];
    },
    handleInputChange(e) {
      this.newCar = e.target.value;
    },
    async onSearch(value) {
      if (value === "" || value === undefined) {
        this.getUserCarInfo();
        return;
      }
      console.log(value);
      this.userInfo.forEach(item => {
        if (value === item.name) {
          value = item.key;
        }
      });
      console.log(value);
      const data = await httpGet(
        SYS_GET_USER_CAR_INFO + "?action=search&info=" + value,
        null
      );
      // this.data=data;
      console.log(data);

      const carInfo = this.carInfo;
      const userInfo = this.userInfo;
      data.forEach((item, index, arr) => {
        arr[index].carNumber = [];
        userInfo.forEach(user => {
          if (user.key == item.user) {
            arr[index].userName = user.name;
          }
        });
        item.car.forEach(k => {
          carInfo.forEach(car => {
            if (car.key === k) {
              arr[index].carNumber.push(car.number);
            }
          });
        });
      });
      this.data = data;
    },
    handleAdd(e) {
      this.disableFlag = true;
      console.log(e);
      ++key;
      const record = {
        key: key,
        user: "",
        car: [],
        carNumber: [],
        userName: "",
        recordAddFlag: true
      };
      this.data.push(record);
    },
    handleChange(e, record) {
      record.userName = e.target.value;
    },
    async removeUser(record) {
      console.log(record);
      await httpGet(
        SYS_GET_USER_CAR_INFO + "?action=delete&info=" + JSON.stringify(record),
        null
      );
      this.getUserCarInfo();
    }
  },
  async created() {
    const carInfo = await httpGet(SYS_GET_CAR_INFO + "?action=get", null);
    const { data: userInfo } = await httpGet(
      SYS_GET_USER_INFO + "?action=get",
      null
    );
    this.carInfo = carInfo;
    this.userInfo = userInfo;
    this.getUserCarInfo();
  }
};
</script>

<style scoped>
.ant-tag {
  margin: 5px;
}
.ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  padding-top: 11px;
}

input,
button,
select,
optgroup,
textarea {
  margin-right: 10px;
}

/deep/.ant-btn-lg {
  width: 80px !important;
}
</style>
